package me.pplay.playtalk.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import me.pplay.playtalk.ApplicationTrans;
import me.pplay.playtalk.R;
import me.pplay.playtalk.activity.friends.DiscoverActivity;
import me.pplay.playtalk.activity.friends.FriendsActivity;
import me.pplay.playtalk.activity.setting.SettingActivity;
import me.pplay.playtalk.adapter.HomeAdapter;
import me.pplay.playtalk.adapter.MessageAdapter;
import me.pplay.playtalk.bean.Chat;
import me.pplay.playtalk.bean.ChattingRecord;
import me.pplay.playtalk.callback.SizeCallBackForMenu;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.database.ChatListDb;
import me.pplay.playtalk.database.FriendDb;
import me.pplay.playtalk.net.ConnectivityManagerUtil;
import me.pplay.playtalk.net.SkyidOperation;
import me.pplay.playtalk.protocol.DataCallBack;
import me.pplay.playtalk.protocol.PhbBackUp;
import me.pplay.playtalk.protocol.TpChat;
import me.pplay.playtalk.protocol.TpFile;
import me.pplay.playtalk.protocol.bean.RspData;
import me.pplay.playtalk.protocol.bean.TPBuddyinfo;
import me.pplay.playtalk.protocol.bean.TpFileData;
import me.pplay.playtalk.service.PlayTalkService;
import me.pplay.playtalk.service.SmsRecevier;
import me.pplay.playtalk.util.AsyncImageLoader;
import me.pplay.playtalk.util.AsyncImageLoader.ImageCallback;
import me.pplay.playtalk.util.BuddyInfoUtil;
import me.pplay.playtalk.util.ComparatorChat;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.util.PlayTalkUtil;
import me.pplay.playtalk.util.ServiceUtil;
import me.pplay.playtalk.util.SkyUtil;
import me.pplay.playtalk.util.UserInfo;
import me.pplay.playtalk.util.fileUtil.ChattingRecordFile;
import me.pplay.playtalk.view.DialogMenu;
import me.pplay.playtalk.view.MenuHorizontalScrollView;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class HomeActivity extends BaseActivity implements OnClickListener{

	
	private ListView listView;
	private EditText search_et;
	private LinearLayout layout_home;
	private RelativeLayout layout_bar, layout_search;
	private ImageButton newConversationBtn, searchBtn;
	 
	private final int SETADAPTER		= 1;
	private final int GETLIST			= 2;
	private final int DELETEDATA		= 3;
	private int clickPosition			= 0;
	private final int HOME_SHOW			= 5;
	private MessageAdapter messageAdapter;
	private ChatListDb dbChat;
	private FriendDb dbFriend;
	private List<Chat> searchList;
	private List<Chat> mList;
	private List<Chat> groupList;
	private DialogMenu chatItemDialog;
	private ComparatorChat	mComparatorchat;
	private ProgressDialog progressDialog;
	private TpChat tpChat;
	
	private final int FINISH = 4;
	private ImageView icon;
	private TextView name, signature;
	private ListView menuList;
	private HomeAdapter adapter;
	private AsyncImageLoader imageLoader;
	private int sdkVersion = 0;
	private TPBuddyinfo myinfo;
	
	private MenuHorizontalScrollView scrollView;
	private View[] children;
	private View menuView;
	private ImageButton menuBtn;
	
	private SmsRecevier recevier;   
	private Timer recevierTimer;   
	String Smsuuid;
	TimerTask timerTask;
    private boolean isregiset = false;   
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    private ProgressDialog smsProgressDialog;
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SETADAPTER:
				if(messageAdapter == null){
					messageAdapter	= new MessageAdapter(HomeActivity.this, searchList, imageLoader);
					listView.setAdapter(messageAdapter);
				}else{
					messageAdapter.notifyDataSetChanged();
				}
				break;
			case Globals.SETMESSAGE_UPDATEPBK:
				smsProgressDialog.dismiss();
				if(msg.arg1 == 1){
					showToast("update ok");
				}else{
					showToast("update err");
				}
				break;
			case Globals.SETMESSAGE_RECVIE_SMS:
				if(msg.arg1 == 1){
					Bundle bundle = msg.getData();
					String sender = bundle.getString("sender");
					String content = bundle.getString("content");
					LogManager.LogShow("HomeActivity", "sender=" + sender + ",content=" + content
							+ ",Smsuuid=" + Smsuuid);
					if(Smsuuid!=null&&content.equals(Smsuuid)){
						//验证成功，发送
						smsProgressDialog.dismiss();
						tpChat.tp_chat_bind_mobile_number(sender);
						recevierTimer.cancel();
						phoneVerificationDlg(R.string.phoneverification_sync);
					}
				}else{
					if (smsProgressDialog!=null)
						smsProgressDialog.dismiss();
					if (recevierTimer!=null)
						recevierTimer.cancel();
					phoneVerificationDlg(R.string.phoneverification_timeout);
				}
				break;
			case Globals.SETMESSAGE_GROUP_CHANGE:
				groupList = (List<Chat>)msg.getData().get("obj");
				getList();
				break;
			case Globals.SETMESSAGE_CHANGE:
			case GETLIST:
				getList();
				break;
			case Globals.SETADAPTER:
				Chat chat = (Chat)msg.getData().getSerializable("obj");
				if(chat != null){
					mList.add(1, chat);
					searchList.add(1, chat);
					handler.sendEmptyMessage(SETADAPTER);
				}
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_OK:{
				progressDialog.dismiss();
				break;
			}
			case PlayTalkUtil.PLAYTALK_LOGIN_ERR: {
				progressDialog.dismiss();
				RspData rspdata = (RspData) msg.obj;
				showToast(rspdata.getString() == null ? "SignIn Unkown err" : rspdata.getString());
			}
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_TIMEOUT:
				progressDialog.dismiss();
				showToast(getString(R.string.net_timeout));
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_WAITING:
				break;
			case DELETEDATA:
				deleteData((Chat)msg.getData().get("chat"));
				break;
			case FINISH:
				HomeActivity.this.finish();
				if (sdkVersion >= 5) 
				   overridePendingTransition(R.anim.noanim, R.anim.left_out);
				break;
			case HOME_SHOW:
				if(layout_home.getVisibility() == View.GONE);
					layout_home.setVisibility(View.VISIBLE);
				break;
			}
		}
		
	};

	private void registerSmsRecevier() {
		IntentFilter filter = new IntentFilter(ACTION);
		filter.setPriority(2147483647);// 设置优先级最大
		registerReceiver(recevier, filter);
		isregiset = true;
	}

	private void unregisterSmsRecevier() {
		if (recevier != null && isregiset) {
			unregisterReceiver(recevier);
			isregiset = false;
		}
	}

	
	private void phoneVerificationDlgWaiting()
	{
		smsProgressDialog = ProgressDialog.show(HomeActivity.this, getString(R.string.loading), getString(R.string.waittng), true, false); 
		smsProgressDialog.show();
		recevierTimer = new Timer();
		timerTask = null;
		timerTask = new TimerTask() {
			public void run() {
				Message message = new Message();
				message.what = Globals.SETMESSAGE_RECVIE_SMS;
				message.arg1 = 0;
				handler.sendMessage(message);
			}
		}; 
		recevierTimer.schedule(timerTask, 15*1000);
	}
	private void updataPbk()
	{
		smsProgressDialog = ProgressDialog.show(HomeActivity.this, getString(R.string.loading), getString(R.string.waittng), true, false); 
		smsProgressDialog.show();
		PhbBackUp pbk = new PhbBackUp(getApplicationContext());
		pbk.updatePhb(getApplicationContext(), SkyidOperation.getUserName(getApplicationContext()),
				UserInfo.getImsi(),UserInfo.getImei(), new DataCallBack() {
					
					@Override
					public void Callback(int result, RspData resultdata, Object obj) {
						// TODO Auto-generated method stub
						LogManager.LogShow("HomeActivity", "PhbBackUp  Callback result= " + result );
						if (result == TpFile.FILE_SERVER_UP_PROGRESS) {
							TpFileData pFile	= (TpFileData)obj;
							if(pFile == null) return;
							int progress 		= (pFile.getFileOffset()* 100)/pFile.getFileSize();
							LogManager.LogShow("HomeActivity", "tp_file_upload  progress:"+progress);
							if(progress == 100){
								Message message = new Message();
								message.what = Globals.SETMESSAGE_UPDATEPBK;
								message.arg1 = 1;
								handler.sendMessage(message);
							}
						}else{ //上传失败
							Message message = new Message();
							message.what = Globals.SETMESSAGE_UPDATEPBK;
							message.arg1 = 0;
							handler.sendMessage(message);
						}
					}
				});
		
	}
	private void phoneVerificationDlg(int stringId)
	{
		// TODO Auto-generated method stub
		LayoutInflater inflater = getLayoutInflater();
		final int strId = stringId;
		final View layout = inflater.inflate(R.layout.layout_phoneverification, (ViewGroup) findViewById(R.id.phoneverification_dialog));
		TextView textview = (TextView) layout.findViewById(R.id.phoneverification_textview);
		EditText editText1 = (EditText) layout.findViewById(R.id.phonenum_edit);
		textview.setText(getResources().getString(strId));
		LogManager.LogShow("HomeActivity", "phoneVerificationDlg string" + getResources().getString(strId));
		if(R.string.phoneverification_sync == strId){
			editText1.setVisibility(View.GONE);
		}else{
			editText1.setVisibility(View.VISIBLE);
		}
		AlertDialog show = new AlertDialog.Builder(HomeActivity.this).setTitle(getResources().getString(R.string.phoneverification_title)).setView(layout).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				EditText editText1 = (EditText) layout.findViewById(R.id.phonenum_edit);
				String pnum = editText1.getText().toString().trim();
				if(strId != R.string.phoneverification_sync){
					if (!pnum.equals("") && SkyUtil.checkPhone(pnum)) {
						SmsManager smsManager = SmsManager.getDefault();
						Smsuuid = UUID.randomUUID().toString();
						smsManager.sendTextMessage(pnum, null, Smsuuid, null, null);
						dialog.dismiss();
						phoneVerificationDlgWaiting();
					}
				}else{
					//上传通讯录
					updataPbk();
				}
			}
		}).show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main_menu);
		findViews();
		//登录操作
		tpChat = ((ApplicationTrans) getApplicationContext()).getTpChat();
		if(!PlayTalkUtil.isLogin){
			((ApplicationTrans)getApplicationContext()).tp_exit();
			loginOn();
		}
		
		initDatas();
		clickEvents();
		Bundle bundle=getIntent().getExtras();
		if(bundle!=null&&PlayTalkUtil.isLogin){
			boolean isfirst=bundle.getBoolean("signin");
			if(isfirst/*&&myinfo.getBindingStatus()==0*/)
				phoneVerificationDlg(R.string.phoneverification);
		}
	}
	
	private void findViews(){
		layout_home		= (LinearLayout)findViewById(R.id.layout_home);
		scrollView		= (MenuHorizontalScrollView)findViewById(R.id.mScrollView);
		icon			= (ImageView)findViewById(R.id.icon);
		name			= (TextView)findViewById(R.id.name);
		signature		= (TextView)findViewById(R.id.signature);
		menuList		= (ListView)findViewById(R.id.listview);
		this.menuView	= LayoutInflater.from(this).inflate(R.layout.layout_message, null);
		this.menuBtn 	= (ImageButton)this.menuView.findViewById(R.id.backBtn);
		initScrollView();
		//message
		listView			= (ListView)menuView.findViewById(R.id.listView);
		search_et			= (EditText)menuView.findViewById(R.id.search_et);
		layout_bar			= (RelativeLayout)menuView.findViewById(R.id.layout_bar);
		layout_search		= (RelativeLayout)menuView.findViewById(R.id.layout_search);
//		backBtn				= (ImageButton)menuView.findViewById(R.id.backBtn);
		newConversationBtn	= (ImageButton)menuView.findViewById(R.id.newConversationBtn);
		searchBtn			= (ImageButton)menuView.findViewById(R.id.searchBtn);
	}
	
	protected void initScrollView(){
		View leftView = new View(this);
		leftView.setBackgroundColor(Color.TRANSPARENT);
		children = new View[]{leftView, menuView};
		this.scrollView.initViews(children, new SizeCallBackForMenu(this.menuBtn), this.menuList, handler);
		this.scrollView.setMenuBtn(this.menuBtn);
	}

	private void initDatas(){
		sdkVersion 		= Build.VERSION.SDK_INT;
		myinfo 			= SkyidOperation.getTpBuddyInfo(this, Globals.skyid);
		name.setText(BuddyInfoUtil.getAlias(myinfo));
		
		signature.setText(myinfo==null?"":myinfo.getSignature());
		adapter			= new HomeAdapter(this);
		menuList.setAdapter(adapter);
		
		imageLoader		= new AsyncImageLoader();
		//message
		search_et.addTextChangedListener(new MyTextWatcher());
		imageLoader			= new AsyncImageLoader();
		dbChat				= new ChatListDb(this);
		dbFriend			= new FriendDb(this);
		mList				= new ArrayList<Chat>();
		searchList			= new ArrayList<Chat>();
		recevier = new SmsRecevier(handler);
	}
	private void dealItemEvent(int position)
	{
		if(position == 0){
			scrollView.clickMenuBtn();
			if(layout_search.getVisibility() == View.VISIBLE){
				layout_search.setVisibility(View.GONE);
				layout_bar.setVisibility(View.VISIBLE);
				if(searchList.get(0) != null){
					searchList.add(0, null);
					handler.sendEmptyMessage(SETADAPTER);
				}
			}
			return;
		}
		Intent intent = new Intent();
		/*if(position == 0){ //messages
			intent.setClass(HomeActivity.this, MessageActivity.class);
		}else*/ if(position == 1){ //contacts
			intent.setClass(HomeActivity.this, FriendsActivity.class);
		}else if(position == 2){//discovery
			intent.setClass(HomeActivity.this, DiscoverActivity.class);
		}else if(position == 3){ //community
			intent.setClass(HomeActivity.this, CommunityActivity.class);
		}else if(position == 4){
			intent.setClass(HomeActivity.this, SettingActivity.class);
		}
//		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
//		handler.sendEmptyMessage(FINISH);
	}
	private void clickEvents(){
		menuList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				dealItemEvent(arg2);
			}
		});
		menuBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				handler.sendEmptyMessage(HOME_SHOW);
				scrollView.clickMenuBtn();
			}
		});
		
		searchBtn.setOnClickListener(this);
		newConversationBtn.setOnClickListener(this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Chat chat = searchList.get(position);
				Intent intent = new Intent();
				if(chat == null && position == 0){ //通知
					intent.setClass(HomeActivity.this, NotificationActivity.class);
				}else{
					if(chat.getType() == 1)
						dbFriend.delete(chat.get_id());
					Bundle bundle = new Bundle();
					bundle.putString("from", "tpbuddyinfo");
					bundle.putInt("skyid", chat.getSkyid());
					bundle.putString("icon", chat.getIcon());
					bundle.putInt("chat_type", chat.getType());
					bundle.putSerializable("skyname", chat.getName()); 
					intent.putExtras(bundle);
					intent.setClass(HomeActivity.this, ChatConversationActivity.class);
				}
				startActivity(intent);
			}
		});
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				clickPosition = position;
				if(clickPosition == 0)
					return false;
				
				if(chatItemDialog == null){
					chatItemDialog = new DialogMenu(HomeActivity.this, HomeActivity.this.findViewById(R.id.rootView), 
							R.drawable.dialog_icon, getString(R.string.chatting_item), new int[]{R.drawable.dialog_view_details_icon, R.drawable.dialog_delete}, getResources().getStringArray(R.array.array_message_menu), new DataCallBack(){

						@Override
						public void Callback(int result, RspData resultdata, Object obj) {
							chatItemDialog.show(false);
							
							if(searchList.size() <= clickPosition)
								return;
							Chat cr	= searchList.get(clickPosition);
							if(cr == null)
								return;
							if(result == 0){ //View Detail
//								if(clip == null)
//									clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
//								clip.setText(cr.content);
							}else{//delete
								mList.remove(cr);
								searchList.remove(clickPosition);
								handler.sendEmptyMessage(SETADAPTER);
								Message msg = new Message();
								msg.what 	= DELETEDATA;
								Bundle bundle = new Bundle();
								bundle.putSerializable("chat", cr);
								
								msg.setData(bundle);
								handler.sendMessage(msg);
							}
						}
					});
					
				}
				chatItemDialog.show(true);
				return false;
			}
		});
		
	}

	
	private void setIcon(){
		TPBuddyinfo buddyinfo 	= SkyidOperation.getTpBuddyInfo(this, Globals.skyid);

		try {
			if(buddyinfo == null){
				icon.setBackgroundResource(R.drawable.class.getDeclaredField("avatar0").getInt(this));
			}else{
				int avatar_sid 	= buddyinfo.getAvatar_sid();
				if(buddyinfo.getAvatar_fpath().equals("")){
					String name 	= "";
					if(avatar_sid == 0){
						name = buddyinfo.getSex() == 1?"avatar0":"avatarf";
					}else{
						name = "avatar"+avatar_sid;
					}
					icon.setBackgroundResource(R.drawable.class.getDeclaredField(name).getInt(this));
				}else{
					Bitmap bitmap 	= imageLoader.loadBitmap("http://" + new ApplicationTrans().getTpChat().tp_chat_gethttpaddr_data(avatar_sid) + "/" + buddyinfo.getAvatar_fpath(), new ImageCallback() {
						
						@Override
						public void imageLoaded(Bitmap imageBitmap, String imageUrl) {
							if(imageBitmap != null)
								icon.setImageBitmap(imageBitmap);
						}
					});
					
					if(bitmap != null)
						icon.setImageBitmap(bitmap);
				}
			}
		} catch (Exception e) {
			
		}
	}

	
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
//		case R.id.backBtn:
//			if(layout_search.getVisibility() == View.VISIBLE){
//				layout_bar.setVisibility(View.VISIBLE);
//				layout_search.setVisibility(View.GONE);
//				getList();
////				handler.sendEmptyMessage(SETADAPTER);
//			}else{
//				Intent intent = new Intent(HomeActivity.this, HomeActivity.class);
//				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				startActivity(intent);
//				if (sdkVersion >= 5)
//					overridePendingTransition(R.anim.right_in, R.anim.noanim);
//			}
//			break;
		case R.id.searchBtn:
			layout_bar.setVisibility(View.GONE);
			layout_search.setVisibility(View.VISIBLE);
			
			searchList.remove(0);
			handler.sendEmptyMessage(SETADAPTER);
			break;
		case R.id.newConversationBtn:
			Intent intent2 = new Intent(HomeActivity.this, ChatConversationActivity.class);
			intent2.putExtra("from", "newConversation");
			startActivity(intent2);
			break;

		default:
			break;
		}
		
	}
	
	private void compareList(List<Chat> list){
		for(int i = list.size() - 1; i >=0 ; i--){
			Chat chatGroup 	= list.get(i);
			Chat chat 		= dbChat.query(chatGroup.getSkyid());
			if(chat != null){
				chat.setName(chatGroup.getName());
				mList.add(0, chat);
			}else{
				mList.add(0, chatGroup);
			}
		}
		if(mComparatorchat == null)
			mComparatorchat = new ComparatorChat();
		 Collections.sort(mList, mComparatorchat);
	}
	
	private void getList(){
				if(mList != null)
					mList.clear();
				if(searchList != null)
					searchList.clear();
				mList				= dbChat.queryList(0);
				List<Chat> friends  = dbFriend.queryList(1);
				for(int i = friends.size() - 1; i >=0 ; i--){
					mList.add(0, friends.get(i));
				}
				
				if(groupList != null && groupList.size() > 0 ){
					compareList(groupList);
				}else if(Globals.groupList.size() > 0){
					compareList(Globals.groupList);
				}
				for(int i = 0; i< mList.size(); i++){
					Chat c = mList.get(i);
					if(c != null){
						List<ChattingRecord> clist = ChattingRecordFile.getChattingRecordByFile(c.getSkyid(), 1);
						if(clist.size() > 0){
							ChattingRecord cr = clist.get(0);
							if(cr != null){
								String content = cr.content;
								String type = cr.type;
								if(type.equals("1"))
									content = "(picture)";
								else if(type.equals("2"))
									content = "(vedio)";
								else if(type.equals("3"))
									content = "(audio)";
								c.setMessage(content);
								c.setTime(cr.time);
							}
						}else{
							c.setCount(0);
						}
						searchList.add(c);
					}
				}
				mList.add(0, null);
				searchList.add(0, null);
				handler.sendEmptyMessage(SETADAPTER);
//			}
//		}).start();
	}
	
	private void deleteData(final Chat cr){
		if(cr == null) return;
//		new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
				if(cr.getType() == 0){ 
					dbChat.delete(cr.get_id());
				}else if(cr.getType() == 1){
					dbFriend.delete(cr.get_id());
				}else if(cr.getType() == 5){
					LogManager.LogShow("MessageActivity", "exit conference skyid:"+cr.getSkyid() + "  "+cr.getName());
					tpChat.tp_conference_quit_conference(cr.getName(), cr.getSkyid());
					if(cr.getTime() != null && !cr.getTime().equals(""))
						dbChat.delete(cr.get_id());
					//退出群会话
					if(Globals.groupList != null){
						for(int i = 0; i < Globals.groupList.size(); i++){
							if(cr.getSkyid() == Globals.groupList.get(i).getSkyid()){
								Globals.groupList.remove(i);
							}
						}
					}
				}
				ChattingRecordFile.deleteChattingRecordFile(cr.getSkyid());
//			}
//		}).start();
	}
	
	
	private void loginOn(){
		if(!ConnectivityManagerUtil.isAccessNetwork(this)){
			showToast(getString(R.string.noNet));
			return;
		}
		progressDialog = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.waittng), true, false); 
		progressDialog.show();
		progressDialog.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if(keyCode == KeyEvent.KEYCODE_BACK){
					progressDialog.cancel();
					Globals.skyid = -1;
					handler.sendEmptyMessage(FINISH);
					return true;
				}
				return false;
			}
		});
		UserInfo.setContext(getApplicationContext());
		
		PlayTalkUtil.login((ApplicationTrans) getApplicationContext(), SkyidOperation.getUserName(this), SkyidOperation.getPassword(this),  new DataCallBack() {

			@Override
			public void Callback(int result, RspData resultdata, Object obj) {
				Message msg = new Message(); 
				msg.what = result; 
				msg.obj = resultdata;
				if (PlayTalkUtil.PLAYTALK_LOGIN_OK == result) {
					msg.obj = obj;
					LogManager.LogShow("MessageActivity", "PLAYTALK_LOGIN_OK Globals.skyid = " + Globals.skyid);
				} else if (PlayTalkUtil.PLAYTALK_LOGIN_ERR == result) {
					LogManager.LogShow("MessageActivity", "PLAYTALK_LOGIN_ERR");
				} else if (PlayTalkUtil.PLAYTALK_LOGIN_TIMEOUT == result) {
					LogManager.LogShow("MessageActivity", "PLAYTALK_LOGIN_TIMEOUT");
				} else if (PlayTalkUtil.PLAYTALK_LOGIN_WAITING == result) {
					msg.obj = obj;
					LogManager.LogShow("MessageActivity", "PLAYTALK_LOGIN_WAITING");
				}
				handler.sendMessage(msg);
			}
		});		 
	}
	
	class MyTextWatcher implements TextWatcher{

		@Override
		public void afterTextChanged(Editable s) {
			
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if(mList == null)
				return;
			searchList.clear();
			int countF = mList.size();
			for(int i = 0; i<countF; i++){
				Chat chat = mList.get(i);
				if(chat != null){
					if(chat.getName().toLowerCase().indexOf(s.toString().trim().toLowerCase()) != -1){
						searchList.add(chat);
					}
				}
			}
			handler.sendEmptyMessage(SETADAPTER);
		}
		
	}
	
	@Override
	protected void onStart() {
		menuList.setAdapter(new HomeAdapter(this));
		setIcon();
		if(PlayTalkService.getInstance() == null)
			ServiceUtil.startService(this);
		if(PlayTalkService.getInstance() !=null){
			PlayTalkService.getInstance().setIsMessage(true);
			PlayTalkService.getInstance().setHandler(handler);
		}
		registerSmsRecevier();
		super.onStart();
	}

	public void getWindowMana() {
		if(Globals.width == 0){
			DisplayMetrics dm = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			Globals.width = dm.widthPixels;
			Globals.height = dm.heightPixels;
			Globals.density = dm.density;
		}
	}
	@Override
	protected void onRestart() {
		getWindowMana();
		super.onRestart();
	}


	@Override
	protected void onResume() {
		super.onResume();
		if(!MenuHorizontalScrollView.menuOut)
			handler.sendEmptyMessage(GETLIST);
	}
	
	@Override
	protected void onStop() {
		PlayTalkService.getInstance().setIsMessage(false);
		unregisterSmsRecevier();
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mList = null;
		searchList = null;
	}
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			
//			if(MenuHorizontalScrollView.menuOut == true){
				handler.sendEmptyMessage(HOME_SHOW);
				this.scrollView.clickMenuBtn();
				return true;
//			}
//			if(layout_search.getVisibility() == View.VISIBLE){
//				layout_search.setVisibility(View.GONE);
//				layout_bar.setVisibility(View.VISIBLE);
////				if(searchList.size() > 0 && searchList.get(0) != null){
//					searchList.add(0, null);
////				}
//				handler.sendEmptyMessage(SETADAPTER);
//				return true;
//			}
//			handler.sendEmptyMessage(FINISH);
//			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	

}
